package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.domain.Admin;
import com.tanhua.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 用户登录逻辑
     * @param map
     * @return
     */
    public Map login(Map map) {
        //获取map中的参数
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        //查看验证码是否正确
        String key = Constants.CAP_CODE+uuid;
        String code = redisTemplate.opsForValue().get(key);
        if(StringUtils.isEmpty(verificationCode) || verificationCode.equals(code)){
           throw new BusinessException("验证码错误，请重试");
        }
        redisTemplate.delete(key);
        //查看账号密码是否正确
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername,username);
        Admin admin = adminMapper.selectOne(wrapper);
        password = SecureUtil.md5(password);
        if(admin == null || !password.equals(admin.getPassword())){
            throw new BusinessException("用户名或密码错误");
        }
        //生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id",admin.getId());
        tokenMap.put("username",username);
        String token = JwtUtils.getToken(tokenMap);
        //构造返回值
        Map resMap = new HashMap();
        resMap.put("token",token);
        return resMap;
    }

    /**
     * 获取用户信息
     * @return
     */
    public AdminVo profile() {
        Long userId = AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(userId);
        return AdminVo.init(admin);
    }
}
